﻿require.config({
    paths: {
        Msg: "Scripts/Message/js/Message"
    }
});
require(["Msg"], function (MsgClass) {
    var IsFirstLoad = true
        , tip;

    var Msg = new MsgClass({ URL: "Message/MsgPushHandler.ashx" });

    window.MsgStore = [];
    window.MsgSubscibeEvents = {}; //{订阅ID:{func:回调,context:window}}

    $(function () {
        //根据配置文件控制站内信的显示
        $("<li id='siteLetterLi'>")
        .html('<a class="letter_tt_m" href="#" title="站内信">站内信</a><p id="msgCountor"></p>')
        .click(function () {
            addTabExtend(this, 'Message/MessageList.aspx', '站内信');
        }).insertBefore($("#line-li"));

        //接收站内信
        Msg.receive(function (msg) {
            window.MsgStore = window.MsgStore.concat(msg);
            $("#msgCountor").html(window.MsgStore.length || "");

            //            if (IsFirstLoad) {
            //                IsFirstLoad = false;
            //            } else {
            content = $("<a href='###'>您有" + msg.length + "条新消息，请注意查收。</a>")
                .click(function () {
                    addTabExtend($('#siteLetterLi'), 'Message/MessageList.aspx', '站内信');
                    tip.hide();
                });
            if (!tip) {
                tip = $.ligerDialog.tip({ title: '提示信息', content: content });
            } else {
                tip.set("content", content);
                tip.show();
            }
            //消息分发
            var events = window.MsgSubscibeEvents;
            for (var e in events) {
                events[e].func.call(events[e].context, msg);
            }
            //}
        });
        Msg.run();
    });

    //在控制台输出错误信息
    function print() {
        if (console && console.error) {
            console.error(arguments);
        }
    }

    //获取用户列表
    if (!window.Users) {
        $.get("Message/MsgPushHandler.ashx", { Func: "GetUsers" }, function (data) {
            if (!data || data["error"]) {
                print(data, "站内信用户列表获取失败");
            }
            window.Users = data;
        }, "json");
    }
});